﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Dtos;
using Aioms.Models;
using Furion.DynamicApiController;
using Furion.LinqBuilder;
using Furion.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Aioms.Controllers
{
    /// <summary>
    /// 巡检点巡检项结果上传
    /// </summary>
    [DynamicApiController]
    public class InspectionPointOptionResultController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public InspectionPointOptionResultController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 上传巡检点巡检项结果
        /// </summary>
        /// <param name="ipor"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUploadresult([FromForm] InspectionPointOptionResultDto ipor)
        {
            // 如果当前结果已上传，提示已上传
            bool isAny = await db.Queryable<InspectionPointOptionResult>().Where(iporet => iporet.Woid == ipor.Woid && iporet.Ipid == ipor.Ipid).AnyAsync();
            if (isAny)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该巡检点结果已经存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            await db.Insertable<InspectionPointOptionResult>(ipor.Adapt<InspectionPointOptionResult>()).ExecuteCommandAsync();
            // 更新工单进度
            await db.Updateable<TpWorkOrder>(new TpWorkOrder { Progress = ipor.Progress })
                .UpdateColumns(wo => new { wo.Progress })
                .Where(wo => wo.Id == ipor.Woid).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
